/**
 * Created by wanthering on 2017/8/16.
 */
'use strict'
const mongoose = require('mongoose');
const Audio = mongoose.model('Audio');
const Lesson = mongoose.model('Lesson');

exports.upload = async function (ctx, next) {
  let id = ctx.request.body.id
  let qun = ctx.request.body.qun
  let url = ctx.request.body.url
  let title = ctx.request.body.title
  let desc = ctx.request.body.desc
  let info = ctx.request.body.info
  let admin = ctx.request.body.admin
  let faceUrl = ctx.request.body.faceUrl
  let qunUrl = ctx.request.body.qunUrl
  let posterUrl = ctx.request.body.posterUrl

  if(!id){
    let maxEntity = await Audio.findOne({}).sort({id: -1}).limit(1);

    if(!maxEntity || !maxEntity.id){
      id = 1
    }else{
      id = maxEntity.id + 1
    }
    let audioEntity = new Audio({id,qun,url,info,admin,title,desc,faceUrl,qunUrl,posterUrl})
    await audioEntity.save()
    ctx.redirect('/audios/'+id)
  }else{
    let audioEntity = await Audio.findOne({id})
    audioEntity.qun = qun
    audioEntity.url = url
    audioEntity.title = title
    audioEntity.admin = admin
    audioEntity.desc = desc
    audioEntity.info = info
    audioEntity.faceUrl = faceUrl
    audioEntity.qunUrl = qunUrl
    audioEntity.posterUrl = posterUrl
    await audioEntity.save()
    ctx.redirect('/audios/'+id)
  }
}

exports.mainPage = async (ctx, next) => {
  console.log(ctx.params.id)
  let id = ctx.params.id
  let audioEntity = await Audio.findOne({id})
  let lessonEntity = await Lesson.findOne({id})
  let lesson = lessonEntity?lessonEntity._id:null
  if(!audioEntity){
    ctx.body = '找不到相应的资源'
  }else{
    let {qun,url,title,desc,admin,faceUrl,qunUrl,posterUrl,info} = audioEntity
    await ctx.render('audio',{id,qun,lesson,admin,url,title,desc,info,faceUrl,posterUrl,qunUrl})
  }
}


exports.qrcode = async (ctx, next) => {
  console.log(ctx.params.id)
  let id = ctx.params.id
  let audioEntity = await Audio.findOne({id})
  if(!audioEntity){
    ctx.body = '找不到相应的资源'
  }else{
    let {qun,url,title,desc,faceUrl,posterUrl,qunUrl} = audioEntity
    await ctx.render('qrcode',{id,qun,posterUrl,url,title,desc,faceUrl,qunUrl})
  }
}

exports.change = async (ctx, next) => {
  let id = ctx.params.id
  let audioEntity = await Audio.findOne({id})
  let lessonEntity = await Lesson.findOne({id})
  let haveLesson = false
  if(lessonEntity){
    haveLesson = true
  }
  if(!audioEntity) {
    ctx.body = '找不到相应的资源'
  }else{
      let {qun,url,title,desc,faceUrl,admin,qunUrl,posterUrl,info} = audioEntity
      await ctx.render('upload',{haveLesson,id,qun,info,admin,url,title,desc,faceUrl,posterUrl,qunUrl})
    }
}

exports.new = async (ctx, next) => {
  let id
  let maxEntity = await Audio.findOne({}).sort({id: -1}).limit(1);

  if(!maxEntity || !maxEntity.id){
    id = 1
  }else{
    id = maxEntity.id + 1
  }

  await ctx.render('upload',{newId:id})
}